package com.magictower.primary.activity;

import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.magictower.primary.R;
import com.magictower.primary.common.SPConstant;


/**
 * 拖动视图控件
 *
 * @author kejunzhan
 * @since 2017/12/14
 */

public class DragViewActivity extends AppCompatActivity {

    private int startX;
    private int startY;
    private TextView tvTop;
    private TextView tvBottom;
    private TextView tvDrag;
    long[] mHits = new long[2];// 数组长度表示要点击的次数
    private SharedPreferences mPref;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drag_view);

        tvTop = (TextView) findViewById(R.id.tv_top);
        tvBottom = (TextView) findViewById(R.id.tv_bottom);
        tvDrag = (TextView) findViewById(R.id.tv_drag);

        mPref = getSharedPreferences(SPConstant.CONFIG, MODE_PRIVATE);

        int toastX = mPref.getInt(SPConstant.TOAST_X, 0);
        int toastY = mPref.getInt(SPConstant.TOAST_Y, 0);

        /**
         * 获取状态栏高度——方法1
         * */
        int statusBarHeight1 = -1;
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
        }
        Log.e("KJ", "状态栏-方法1:" + statusBarHeight1);
        /**
         * 获取状态栏高度——方法2
         * 反射方法去获取
         * */
        int statusBarHeight2 = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusBarHeight2 = getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.e("KJ", "状态栏-方法2:" + statusBarHeight2);

        //屏幕
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        Log.e("KJ", "屏幕高:" + dm.heightPixels);
        Log.e("KJ", "屏幕宽:" + dm.widthPixels);

        //应用区域
        Rect outRect1 = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect1);
        Log.e("KJ", "应用区顶部" + outRect1.top);
        Log.e("KJ", "应用区高" + outRect1.height());

        //View绘制区域
        Rect outRect2 = new Rect();
        getWindow().findViewById(Window.ID_ANDROID_CONTENT).getDrawingRect(outRect2);
        Log.e("KJ", "View绘制区域顶部-错误方法：" + outRect2.top);   //不能像上边一样由outRect2.top获取，这种方式获得的top是0，可能是bug吧
        int viewTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();   //要用这种方法
        Log.e("KJ", "View绘制区域顶部-正确方法：" + viewTop);
        Log.e("KJ", "View绘制区域高度：" + outRect2.height());

        final int winWidth = getWindowManager().getDefaultDisplay().getWidth();
        final int winHeight = getWindowManager().getDefaultDisplay().getHeight() - statusBarHeight1;

        if (toastY > winHeight / 2) {
            // 上边显示,下边隐藏
            tvBottom.setVisibility(View.INVISIBLE);
            tvTop.setVisibility(View.VISIBLE);
        } else {
            tvBottom.setVisibility(View.VISIBLE);
            tvTop.setVisibility(View.INVISIBLE);
        }

        //获取拖动框的背景
        int style = mPref.getInt(SPConstant.TOAST_STYLE, 0);
        tvDrag.setBackgroundResource(SPConstant.ITEMS_ID[style]);
        //获取布局对象
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) tvDrag.getLayoutParams();
        layoutParams.leftMargin = toastX;//设置左边距
        layoutParams.topMargin = toastY;//设置上边距
        tvDrag.setLayoutParams(layoutParams);//重新定义位置

        tvDrag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
                mHits[mHits.length - 1] = SystemClock.uptimeMillis();// 开机后开始计算的时间
                if (mHits[0] >= (SystemClock.uptimeMillis() - 500)) {
                    // 把图片居中
                    tvDrag.layout(winWidth / 2 - tvDrag.getWidth() / 2,
                            tvDrag.getTop(), winWidth / 2 + tvDrag.getWidth()
                                    / 2, tvDrag.getBottom());
                }
            }
        });

        tvDrag.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startX = (int) event.getRawX();
                        startY = (int) event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        int endX = (int) event.getRawX();
                        int endY = (int) event.getRawY();

                        // 计算移动偏移量
                        int dx = endX - startX;
                        int dy = endY - startY;

                        // 更新左上右下距离
                        int l = tvDrag.getLeft() + dx;
                        int r = tvDrag.getRight() + dx;
                        int t = tvDrag.getTop() + dy;
                        int b = tvDrag.getBottom() + dy;

                        // 判断是否超出屏幕边界, 注意状态栏的高度
                        if (l < 0 || r > winWidth || t < 0 || b > winHeight) {
                            break;
                        }
                        if (t > winHeight / 2) {
                            // 上边显示,下边隐藏
                            tvBottom.setVisibility(View.INVISIBLE);
                            tvTop.setVisibility(View.VISIBLE);
                        } else {
                            tvBottom.setVisibility(View.VISIBLE);
                            tvTop.setVisibility(View.INVISIBLE);
                        }
                        tvDrag.layout(l, t, r, b);//重新定义位置
                        //重新初始化坐标
                        startX = (int) event.getRawX();
                        startY = (int) event.getRawY();
                        break;
                    case MotionEvent.ACTION_UP:
                        //保存数据
                        SharedPreferences.Editor editor = mPref.edit();
                        editor.putInt(SPConstant.TOAST_X, tvDrag.getLeft());
                        editor.putInt(SPConstant.TOAST_Y, tvDrag.getTop());
                        editor.apply();
                        break;
                }
                return false;
            }
        });

    }
}
